package es.uc3m.setichat.xmlparser;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import es.uc3m.setichat.format.Contacto;
import es.uc3m.setichat.mensaje.ContentMessage;

public class XmlDescompose {
	
	public static Document getNode(Node node) throws ParserConfigurationException{
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setNamespaceAware(true);
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document nodeDoc = builder.newDocument();
		nodeDoc.setXmlStandalone(true);
		Node importedNode = nodeDoc.importNode(node, true);
		nodeDoc.appendChild(importedNode);
		return nodeDoc;
	}
	
	public static Document headerDescompose(String msgXml) throws ParserConfigurationException, SAXException, IOException{
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //un factory
		DocumentBuilder builder = factory.newDocumentBuilder(); //el documento
		Document document = builder.parse(new InputSource(new StringReader(msgXml)));
		document.getDocumentElement().normalize();
		NodeList nodes = document.getElementsByTagName("header");
		/*En este nodo tengo toda la cabezera*/
		Node headerNode = nodes.item(0);
		return getNode(headerNode);
	}
	
	public static Document contentDescompose(String msgXml) throws ParserConfigurationException, SAXException, IOException{
		
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //un factory
		DocumentBuilder builder = factory.newDocumentBuilder(); //el documento
		Document document = builder.parse(new InputSource(new StringReader(msgXml)));
		document.getDocumentElement().normalize();
		NodeList nodes = document.getElementsByTagName("content");
		/*En este nodo tengo todo el content*/
		Node nodeContent = nodes.item(0);	 
		return getNode(nodeContent);
	}
	
	public static Document signatureDescompose(String msgXml) throws ParserConfigurationException, SAXException, IOException{
		
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //un factory
		DocumentBuilder builder = factory.newDocumentBuilder(); //el documento
		Document document = builder.parse(new InputSource(new StringReader(msgXml)));
		document.getDocumentElement().normalize();
		NodeList nodes = document.getElementsByTagName("signature");
		/*En este nodo tengo todo el content*/
		Node nodeSignature = nodes.item(0);	 
		return getNode(nodeSignature);
	}
	
	
	/**
	 * @param args
	 * @throws IOException 
	 * @throws SAXException 
	 * @throws ParserConfigurationException 
	 */
	public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
		
		String msgXml="<message><header><idSource>BF73FDD51154B37DA605E045FEA6801E</idSource><idDestination>setichat@appspot.com</idDestination><idMessage>59653547263911483661359531466704092258</idMessage><type>2</type><encrypted>false</encrypted><signed>false</signed></header><content><mobileList><mobile>100030456.100030457.100030458</mobile><mobile>100081643.100080710.100080835</mobile><mobile>100081643.100080835.100080710</mobile></mobileList></content></message>";
		String msgXml2 ="<?xml version=\"1.0\" encoding=\"UTF-8\"?><message><header><idSource>setichat@appspot.com</idSource><idDestination>100012345.100056789</idDestination><idMessage>2d46f3c49a2c6b7a2</idMessage><type>3</type><encrypted>false</encrypted><signed>false</signed></header><content><contactList><contact><mobile>100015645.100011112</mobile><nick>Puta</nick></contact><contact><mobile>100015645.100011113</mobile><nick>Zorra</nick></contact><contact><mobile>100015645.100011114</mobile><nick>Guarra</nick></contact></contactList></content></message>";
		Document header=headerDescompose(msgXml2);
		Document content=contentDescompose(msgXml2);
		try{
		TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        //transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"no");
        StringWriter writer = new StringWriter();
//        transformer.transform(new DOMSource(header), new StreamResult(writer));
//        
//        String headerxml = writer.getBuffer().toString();
//        System.out.println(headerxml);
        transformer.transform(new DOMSource(content), new StreamResult(writer));;
        String contentxml = writer.getBuffer().toString();
        System.out.println(contentxml);
		}catch(Exception e){
			e.printStackTrace();
		}
		ContentMessage listaContactos = new ContentMessage();
		listaContactos.setDocument(content);
		ArrayList<Contacto> contactos=listaContactos.getContacList();
		
//		Iterator<Contacto> nombreIterator = contactos.iterator();
		
		for(Contacto contacto : contactos){
			
			System.out.println(contacto.getNick());
			System.out.println(contacto.getMobile());
			
		}
		
//        while( i.hasNext() && contador< ){
//       	 
//       	 auxiliar= contactos.get(contador);
//       	 System.out.println(auxiliar.getNick());
//       	 System.out.println(auxiliar.getMobile());
//       	 contador++;
//        }
//		HeaderMessage nodoHead = new HeaderMessage(header);
//		
//		System.out.println("IDSOURCE: "+nodoHead.getIdSource());
//		System.out.println("IDDESTINATION: "+nodoHead.getIdDestination());
//		System.out.println("IDMESSAGE: "+nodoHead.getIdMessage());
//		System.out.println("TYPE: "+nodoHead.getType());
//		System.out.println("ENCRYPTED: "+nodoHead.isEncrypted());
//		System.out.println("SIGNED: "+nodoHead.isSigned());
	}

}
